import util from '../../utils/util.js';
import http from '../../apis/api.js';
let self;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ownNo:'',
    couponInfo:{
      exCode:'',
      phone:'',
      storeNo:''
    },
    storeList:[],
    index:0,
    error:{
      exCode:'',
      phone:''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    self=this;
    self.data.ownNo = options.ownNo;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  getCode(e){
    wx.scanCode({
      success(res) {
        self.data.couponInfo.exCode = res.result;
        self.setData({
          couponInfo: self.data.couponInfo
        })
        self.getScanInfo();
      }
    })
  },
  getValus(e){
    let type = e.currentTarget.dataset.type;
    switch (type) {
      case 'exCode':
        self.data.couponInfo.exCode = e.detail.value;
        if (self.data.couponInfo.exCode!=''){
          self.getScanInfo();
        }
        break;
      case 'phone':
        self.data.couponInfo.phone = e.detail.value;
        break;
    }
    self.setData({
      couponInfo: self.data.couponInfo
    })
  },
  checked(name) {
    switch (name) {
      case 'exCode':
        self.data.error.exCode = self.data.couponInfo.exCode.length > 0 ? '' : '代金券编码不能为空';
        return self.data.couponInfo.exCode.length > 0 ? true : false;
        break;
      case 'phone':
        if (self.data.couponInfo.phone.length>0&&!util.reg.phone.test(self.data.couponInfo.phone)) {
          self.data.error.phone = "请输入正确的手机";
          return false;
        }
        self.data.error.phone = '';
        return true;
        break;
    }
  },
  submit(e){
    if (self.checked('exCode') && self.checked('phone')){
      self.setData({
        error: self.data.error
      })
      let data={
        exCode: self.data.couponInfo.exCode,
        ownNo: self.data.ownNo,
        storeNo: self.data.couponInfo.storeNo
      }
      http.sweepCode(data).then(res=>{
       if(res.code==0){
         wx.showToast({
           title: '消费成功',
           icon: 'success',
           duration: 2000,
           complete(){
             wx.navigateBack();
           }
         })
       }
      })
    }else{
      self.setData({
        error: self.data.error
      })
    }
  },
  bindPickerChange(e){
    self.data.index=e.detail.value;
    self.data.couponInfo.storeNo = self.data.storeList[self.data.index].storeNo
    self.setData({
      index: self.data.index,
      couponInfo: self.data.couponInfo
    })
  },
  getScanInfo(){
    http.getScanInfo(`?exCode=${self.data.couponInfo.exCode}&ownNo=${self.data.ownNo}`).then(result => {
      self.data.storeList = result.data.storeList;
      self.data.couponInfo.storeNo = self.data.storeList[self.data.index].storeNo
      self.setData({
        storeList: self.data.storeList
      })
    })
  }
})